package unzip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Unzipper {

	private String INPUT_ZIP_FILE;
	private String OUTPUT_FOLDER;

	public Unzipper(String zipFile, String outputFolder) {
		this.INPUT_ZIP_FILE = zipFile;
		this.OUTPUT_FOLDER = outputFolder;
	}

	public void unZipIt() {

		byte[] buffer = new byte[1024];

		try {

			// create output directory is not exists
			File folder = new File(OUTPUT_FOLDER);
			if (!folder.exists()) {
				folder.mkdir();
			}

			// get the zip file content
			ZipInputStream zis = new ZipInputStream(new FileInputStream(INPUT_ZIP_FILE));
			// get the zipped file list entry
			ZipEntry ze = zis.getNextEntry();

			while (ze != null) {

				String fileName = ze.getName();
				File newFile = new File(OUTPUT_FOLDER + File.separator + fileName);
				
				System.out.println("file unzip : " + newFile.getAbsoluteFile());

				// create all non exists folders
				// else you will hit FileNotFoundException for compressed folder
				new File(newFile.getParent()).mkdirs();

				if(ze.isDirectory()) {
					newFile.mkdir();
				} else {
					FileOutputStream fos = new FileOutputStream(newFile);
	
					int len;
					while ((len = zis.read(buffer)) > 0) {
						fos.write(buffer, 0, len);
					}
	
					fos.close();
				}
				ze = zis.getNextEntry();
			}

			zis.closeEntry();
			zis.close();

			System.out.println("Done");

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new Unzipper("swan.zip", "unzippedswan1").unZipIt();
	}
	
}
